package com.eurasia.assignment.service;

import java.time.LocalDateTime;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eurasia.assignment.domain.SubmissionAction;
import com.eurasia.assignment.domain.SubmissionStatus;
import com.eurasia.assignment.infrastructure.entity.SubmissionEntity;
import com.eurasia.assignment.infrastructure.repository.SubmissionRepository;
import com.eurasia.assignment.service.port.in.CreateSubmissionReviewUseCase;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@RequiredArgsConstructor
@Slf4j
public class CreateSubmissionReviewService implements CreateSubmissionReviewUseCase {

    private final SubmissionRepository submissionRepository;

    @Override
    @Transactional
    public void createReview(Long submissionId, SubmissionAction action, String comment, Long reviewerId) {
        // 1. 查找需要评审的提交
        SubmissionEntity submissionEntity = submissionRepository.findById(submissionId)
                .orElseThrow(() -> new SubmissionNotFoundException(submissionId));

        // 2. 根据评审操作类型设置状态
        SubmissionStatus newStatus;
        if (action == SubmissionAction.APPROVE) {
            newStatus = SubmissionStatus.APPROVED;
        } else if (action == SubmissionAction.REJECT) {
            newStatus = SubmissionStatus.REJECTED;
        } else {
            throw new IllegalArgumentException("不支持的评审操作: " + action);
        }

        // 3. 更新评审信息
        submissionEntity.setReviewStatus(newStatus);
        submissionEntity.setReviewResult(comment);
        submissionEntity.setReviewerId(reviewerId);
        submissionEntity.setReviewTime(LocalDateTime.now());

        // 4. 保存更新后的实体
        submissionRepository.save(submissionEntity);
        
        log.info("成功完成提交评审，ID: {}, 操作: {}, 状态: {}", submissionId, action, newStatus);
    }

    // 自定义异常类
    public static class SubmissionNotFoundException extends RuntimeException {
        public SubmissionNotFoundException(Long submissionId) {
            super("找不到指定的提交记录: " + submissionId);
        }
    }
} 